import { getRepository } from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
import { PositionEntity } from '../entity/position.entity';

const positionRepository = getRepository(PositionEntity);

/**
 * 获取职位列表
 */
export async function list(condition: any = {}) {
  return await positionRepository.findAndCount(condition);
}

/**
 * 添加/更新职位
 * @param eid 企业id
 * @param entity
 */
export async function save(eid: string, entity: PositionEntity) {
  const result = await positionRepository.findOne({
    name: entity.name
  });
  // 如果存在此条记录，进行更新
  if (result) {
    const { affected } = await positionRepository.update(result.id, entity);
    return affected;
  }
  entity.id = uuidv4().replace(/-/g, '');
  entity.eid = eid;
  const { raw } = await positionRepository.insert(entity);
  return raw.affectedRows;
}
